package teleradiologia.web;

import com.sun.mail.smtp.SMTPTransport;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MailSender {

	private static final String SMTP_HOST_NAME = "poczta.o2.pl";
	private static final String SMTP_AUTH_USER = "tele-radiologia";
	private static final String SMTP_AUTH_PWD = "koalakoala";

	private static final String emailFromAddress = "tele-radiologia@o2.pl";

	public static void sendMail(Email email) throws Exception {
		MailSender smtpMailSender = new MailSender();
		smtpMailSender
				.postMail(email.getEmailList(), email.getEmailSubjectTxt(),
						email.getEmailMsgTxt(), emailFromAddress);
		System.out.println("Sucessfully Sent mail to All Users");
	}

	public void postMail(String recipients[], String subject, String message,
			String from) throws MessagingException {
		boolean debug = false;
		java.security.Security
				.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

		// Set the host smtp address
		Properties props = new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", SMTP_HOST_NAME);
		props.put("mail.smtp.auth", "true");

		Authenticator auth = new SMTPAuthenticator();
		Session session = Session.getDefaultInstance(props, auth);

		session.setDebug(debug);

		// create a message
		Message msg = new MimeMessage(session);

		// set the from and to address
		InternetAddress

		addressFrom = new InternetAddress(from);
		msg.setFrom(addressFrom);

		InternetAddress[] addressTo = new InternetAddress[recipients.length];
		for (int i = 0; i < recipients.length; i++) {
			addressTo[i] = new InternetAddress(recipients[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addressTo);

		// Setting the Subject and Content Type
		msg.setSubject(subject);
		msg.setContent(message, "text/plain");
		//for (int i = 0; i < 1; i++) {
			SMTPTransport t = new SMTPTransport(session, new URLName("smtp",
					SMTP_HOST_NAME, 25, "", SMTP_AUTH_USER, SMTP_AUTH_PWD));
			t.setStartTLS(true);

			t.connect(SMTP_AUTH_USER, SMTP_AUTH_PWD);
			t.setStartTLS(true);
			t.sendMessage(msg, addressTo);
		//}
	}

	/**
	 * SimpleAuthenticator is used to do simple authentication when the SMTP
	 * server requires it.
	 */
	private class SMTPAuthenticator extends javax.mail.Authenticator {

		public PasswordAuthentication getPasswordAuthentication() {
			String username = SMTP_AUTH_USER;
			String password = SMTP_AUTH_PWD;
			return new PasswordAuthentication(username, password);
		}
	}
}
